package com.celesea.auth.position.service;

import com.celesea.auth.dept.entity.Dept;
import com.celesea.auth.dept.service.DeptService;
import com.celesea.auth.position.dao.PositionDao;
import com.celesea.auth.position.entity.Position;
import com.celesea.auth.position.entity.PositionUser;
import com.celesea.auth.position.vo.PositionVo;
import com.celesea.auth.position.vo.UserPositionVo;
import com.celesea.auth.role.entity.RoleCode;
import com.celesea.framework.dao.Filter;
import com.celesea.framework.entity.BusEntity;
import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.*;
import com.celesea.framework.vo.DictionaryVo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author JackYuan
 * @create 2017-10-28 21:39
 */
@Service
public class PositionServiceImpl extends AbstractBaseService<Position> implements PositionService {

    public static final String PY_CHARS = "pyChars";

    @Autowired
    private PositionDao positionDao;
    @Autowired
    private DeptService deptService;
    @Autowired
    private PositionUserService positionUserService;

    @Override
    public PageData<Position> selectPage(Filter filter, Page page, Sort sort) {
        PageData<Position> positions = super.selectPage(filter, page, sort);
        positions.append(PY_CHARS, positionDao.selectPyChars(filter));
        return positions;
    }

    @Override
    public PositionVo insert(PositionVo entity) {
        Position position = super.insert(entity.toEntity());
        entity.setId(position.getId());
        entity.getUsers().stream().forEach(item -> {
            // 新增的时候部门就是岗位所属部门
            item.setPositionId(entity.getId());
            item.setPositionName(entity.getName());
            item.setDept(entity.getDept());
            item.setExtend(entity.getExtend());
        });
        positionUserService.insertByPosition(entity);
        return entity;
    }

    @Override
    public PositionVo update(PositionVo entity) {
        // when update,can not update company
        Position position = super.selectById(entity.getId());
        if (StringKit.isEmpty(position.getCompany())) {
            entity.setCompany(null);
        } else {
            if (!EnvUtil.hasAnyRoles(RoleCode.ADMIN_SYSTEM)) {
                // 不是系统管理员，需要验证所属公司
                Assert.isTrue(EnvUtil.getCompany().equals(position.getCompany()), "当前公司节点管理员才可以编辑");
            }
            entity.setCompany(position.getCompany());
        }
        super.update(entity.toEntity());
        return entity;
    }

    @Override
    public PositionVo selectById(String id, String deptId) {
        Position position = super.selectById(id);
        PositionVo positionVo = new PositionVo(position);
        if (StringKit.isNotEmpty(position.getDeptId())) {
            Dept dept = deptService.selectById(position.getDeptId());
            positionVo.setDept(new DictionaryVo(dept.getId(), dept.getName()));
        }
        return positionVo;
    }

    @Override
    public PositionVo selectConfig(String id, String deptId) {
        PositionVo positionVo = this.selectById(id, deptId);

        if (StringKit.isEmpty(deptId)) {
            positionVo.setCurrentDept(positionVo.getDept());
        } else {
            Dept currentDept = deptService.selectById(deptId);
            // 当前授权的部门
            positionVo.setCurrentDept(new DictionaryVo(currentDept.getId(), currentDept.getName()));
        }
        // 先查找当前部门的授权岗位
        List<PositionUser> positionUsers = positionUserService.findByPosition(id, deptId);
        if (CollectionKit.isEmpty(positionUsers)) {
            List<String> parentIds = deptService.selectParents(deptId);
            if (CollectionKit.isNotEmpty(parentIds)) {
                // 查找父节点的授权用户
                positionUsers = positionUserService.findByPosition(id, parentIds);
            }
        }
        positionVo.setExtend(Const.Bool.FALSE);
        if (CollectionKit.isNotEmpty(positionUsers)) {
            List<UserPositionVo> showUsers = Lists.newArrayList();
            positionUsers.forEach(item -> {
                if (Const.Bool.isTrue(item.getExtend())) {
                    positionVo.setExtend(item.getExtend());
                }
                showUsers.add(new UserPositionVo(item));
            });
            positionVo.setUsers(showUsers);
        }
        return positionVo;
    }

    @Override
    public PositionVo updateConfig(PositionVo entity) {
        Assert.notNull(entity.getCurrentDept(), "当前授权部门不能为空！");
        List<UserPositionVo> currentUserPositions = Lists.newArrayList();
        if (CollectionKit.isNotEmpty(entity.getUsers())) {
            // 过滤非当前部门的授权岗位
            entity.getUsers().forEach(item -> {
                if (item.getDept() != null
                        && StringKit.isNotEmpty(item.getDept().getId())
                        && item.getDept().getId().equals(entity.getCurrentDept().getId())) {
                    item.setPositionId(entity.getId());
                    item.setPositionName(entity.getName());
                    item.setExtend(entity.getExtend());
                    currentUserPositions.add(item);
                }
            });
        }
        entity.setUsers(currentUserPositions);

        // 子部门下操作岗位授权,只能删除当前子部门下授权的人员
        positionUserService.deleteByPosition(entity);
        // 也只能插入当前子部门的授权人员
        positionUserService.insertByPosition(entity);

        return entity;
    }

    @Override
    public PositionVo buildByDept(String deptId) {
        PositionVo positionVo = new PositionVo();
        Dept dept = deptService.selectById(deptId);
        positionVo.initForCreate(new DictionaryVo(dept.getId(), dept.getName()));
        return positionVo;
    }

    @Override
    public void updateFixCompany(String companyId, List<String> childIds) {
        Example example = new Example(Position.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(BusEntity.TALENT_ID, EnvUtil.getTenantId())
                .andIn("deptId", childIds);
        Position entity = new Position();
        entity.setCompany(companyId);
        positionDao.updateByExampleSelective(entity, example);
    }
}
